package com.java.comprehensive.arithmetic.leecode.easy;

import java.util.HashMap;
import java.util.Objects;
import java.util.Stack;

/**
 * @program: comprehensive-service
 * @description: 有效的括号
 * @author: 窦绍飞
 * @create: 2021-11-03 15:30
 **/
public class LeetCode_20 {

	static class Solution {
		public boolean isValid(String s) {
			if (s != null && s.length() > 0) {
				Stack<Character> characters = new Stack<>();
				for (int i = 0; i < s.length(); i++) {
					switch (s.charAt(i)) {
					case '[':
					case '{':
					case '(':
						characters.push(s.charAt(i));
						break;
					case ']':
						if (characters.empty()) {
							return false;
						}
						Character pop = characters.pop();
						if (!pop.equals('[')) {
							return false;
						}
						break;
					case '}':
						if (characters.empty()) {
							return false;
						}
						Character pop1 = characters.pop();
						if (!pop1.equals('{')) {
							return false;
						}
						break;
					case ')':
						if (characters.empty()) {
							return false;
						}
						Character pop2 = characters.pop();
						if (!pop2.equals('(')) {
							return false;
						}
						break;
					default:
						return false;
					}
				}
				return characters.empty();
			}
			return false;
		}

		public static void main(String[] args) {
			Solution solution = new Solution();
			boolean valid = solution.isValid("[{}][]()");
			System.out.println(valid);
		}
	}

	public static void main(String[] args) {
		isValidtt("()");
	}

	public static boolean isValidtt(String s) {
		if (Objects.equals(s, "") || s.length() % 2 == 1) {
			return false;
		}
		HashMap map = new HashMap(16) {
			{
				put('}', '{');
				put(']', '[');
				put(')', '(');
			}
		};
		Stack<Character> stack = new Stack<>();
		for (int i = 0; i < s.length(); i++) {
			char c = s.charAt(i);
			if (map.containsKey(c)) {
				if (stack.isEmpty() || stack.pop() != map.get(c)) {
					return false;
				}
			} else {
				stack.push(c);
			}
		}
		return stack.isEmpty();
	}
}
